package com.dhecp.project.storage.controller;

import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.DateUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.core.utils.ExportExcelListUtils;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.domain.ModuleNidAndBid;
import com.dhecp.project.common.service.ModuleNidAndBidService;
import com.dhecp.project.storage.domain.*;
import com.dhecp.project.storage.mapper.HwPaymentSonMapper;
import com.dhecp.project.storage.service.HwReconcileCksonService;
import com.dhecp.project.storage.service.HwReconcileKcsonService;
import com.dhecp.project.storage.service.HwReconcileService;
import com.dhecp.project.storage.service.HwReconcileSonService;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.dhecp.project.common.controller.BaseModuleController;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import com.dhecp.common.annotation.Log;
import org.springframework.web.servlet.ModelAndView;

/**
 * 海外仓对账单(HwReconcile)控制层
 *
 * @author fxz
 * @since 2024-03-01 11:09:34
 */
@Controller
@RequestMapping("/storage/hwReconcile")
public class HwReconcileController extends BaseModuleController{
    private String prefix = "storage/hwReconcile";
    private String moduleTable = ModuleTable.HW_RECONCILE;
    private String moduleTable2 = ModuleTable.HW_RECONCILE_SON;
    private String moduleTable3 = ModuleTable.HW_RECONCILE_CKSON;
    private String moduleTable4 = ModuleTable.HW_RECONCILE_KCSON;

    @Autowired
    private HwReconcileService hwReconcileService;

    @Autowired
    private HwReconcileSonService hwReconcileSonService;

    @Autowired
    private HwReconcileCksonService hwReconcileCksonService;

    @Autowired
    private HwReconcileKcsonService hwReconcileKcsonService;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private ModuleNidAndBidService moduleNidAndBidService;

    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

    @Autowired
    private HwPaymentSonMapper hwPaymentSonMapper;

    /**
     *@Description: 打开查询列表页
     *@Param: [params]
     *@return: org.springframework.web.servlet.ModelAndView
     *@Author: fxz
     *@date: 2024-03-01 11:09:34
     */
    @RequiresPermissions("storage:hwReconcile:view")
    @GetMapping()
    public ModelAndView listPage(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("entity", new HwReconcile()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix", prefix + "/hwReconcile"); //页面路径
        params.put("toolBarWidth", 0);
        params.put("checkBox", "yes");

        ModelAndView mv = this.openListPage(params);
        mv.addObject("storage", "hwReconcile");
        mv.setViewName(prefix + "/hwReconcile");
        return mv;
    }

     /**
     *@Description: 查询页 列表数据
     *@Param: [params]
     *@return: com.dhecp.common.core.page.TableDataInfo
     *@Author: fxz
     *@date: 2024-03-01 11:09:34
     */
    @RequiresPermissions("storage:hwReconcile:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        List<HwReconcile> list = new ArrayList<HwReconcile>();
        try {
            list = hwReconcileService.queryList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

     /**
     *@Description: 数据导出Excel
     *@Param: [params]
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: fxz
     *@date: 2024-03-01 11:09:34
     */
    @RequiresPermissions("storage:hwReconcile:export")
    @Log(title = "导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception {
        Map listMap=new HashMap();
        Map fieldListMap=new HashMap();
        List<String> sheetNameList = new ArrayList<>();
        Map<String, Object> params3 = new HashMap<String, Object>();

        params.put("moduleTable", moduleTable);
        params.put("entity", new HwReconcile());

        //海外仓对账单
        List<HwReconcile> hwReconcileList = hwReconcileService.queryList(params);
        listMap.put(0, hwReconcileList);

        params.put("getFieldAttributesType", "export");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        fieldListMap.put(0, fieldList);


        ExportExcelListUtils<Object> util = new ExportExcelListUtils<>(moduleTable,new HwReconcile());

        List<HwReconcileSon> hwReconcileSonListNew = new ArrayList<>();
        List<HwReconcileCkson> hwReconcileCksonListNew = new ArrayList<>();
        List<HwReconcileKcson> hwReconcileKcsonListNew = new ArrayList<>();
        //入库对账信息
        for (HwReconcile hwReconcile :hwReconcileList){
            params3.put("pBid",hwReconcile.getBid());
            params3.put("moduleTable", moduleTable2);
            List<HwReconcileSon> hwReconcileSonList = hwReconcileSonService.queryList(params3);
            for (HwReconcileSon hwReconcileSon :hwReconcileSonList){
                hwReconcileSonListNew.add(hwReconcileSon);
            }

            //出库数据
            params3.put("moduleTable", moduleTable3);
            List<HwReconcileCkson> hwReconcileCksonList = hwReconcileCksonService.queryList(params3);
            for (HwReconcileCkson hwReconcileCkson :hwReconcileCksonList){
                hwReconcileCksonListNew.add(hwReconcileCkson);
            }


            //库存数据
            params3.put("moduleTable", moduleTable4);
            List<HwReconcileKcson> hwReconcileKcsonList = hwReconcileKcsonService.queryList(params3);
            for (HwReconcileKcson hwReconcileKcson :hwReconcileKcsonList){
                hwReconcileKcsonListNew.add(hwReconcileKcson);
            }
        }

        params.put("getFieldAttributesType", "export");
        params.put("moduleTable", moduleTable2);
        params.put("entity", new HwReconcileSon());
        fieldListMap.put(1, dictionaryForFieldService.queryExportFieldList(params));

        params.put("getFieldAttributesType", "export");
        params.put("moduleTable", moduleTable3);
        params.put("entity", new HwReconcileCkson());
        fieldListMap.put(2, dictionaryForFieldService.queryExportFieldList(params));

        params.put("getFieldAttributesType", "export");
        params.put("moduleTable", moduleTable4);
        params.put("entity", new HwReconcileKcson());
        fieldListMap.put(3, dictionaryForFieldService.queryExportFieldList(params));

        listMap.put(0, hwReconcileList);
        listMap.put(1, hwReconcileSonListNew);
        listMap.put(2, hwReconcileCksonListNew);
        listMap.put(3, hwReconcileKcsonListNew);

        sheetNameList.add("海外仓对账单");
        sheetNameList.add("入库对账信息");
        sheetNameList.add("出库对账信息");
        sheetNameList.add("库存对账信息");

        return util.exportExcel(listMap, fieldListMap, sheetNameList, "export");
    }

    /**
     * @Description: 打开制单页
     * @Param: nid 必要参数：单据编码（新增时传默认值 0 ，修改、查看时传单据实际值）
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: fxz
     * @date: 2024-03-01 11:09:34
     */
    @RequiresPermissions("storage:hwReconcile:view")
    @GetMapping("/edit")
    public ModelAndView editPage(@RequestParam Map<String, Object> params) {
        if (params.get("nid") == null || params.get("nid") == "") {
            params.put("nid", "0");
        }
        params.put("moduleTable", moduleTable);
        params.put("entity", new HwReconcile()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        params.put("moduleUrl", prefix); //页面上级路径
        params.put("prefix", prefix + "/hwReconcile_edit"); //页面路径
        Subject userSubject = ShiroUtils.getSubject();
        int enableEdit = 0;
        boolean vType = false;
        if (params.get(enableEdit) == null || "1".equals(params.get(enableEdit).toString())) {
            if (userSubject.isPermitted("storage:hwReconcile:edit")) { //当前登录用户主体是否有修改的权限
                enableEdit = 1;
            }
        }

        try {
            Map<String, Object> headData = new HashMap<String, Object>();        //表头的业务数据
            HwReconcile businessData = hwReconcileService.queryFirstRecord(params);
            if (businessData == null) { //未查询到对应单据，页面初始化值
                ModuleNidAndBid moduleNidAndBid = moduleNidAndBidService.queryModuleNidAndBidInitial(params);
                businessData = new HwReconcile();
                businessData.setNid("0");
                businessData.setBid(moduleNidAndBid.getBid());
                businessData.setCreateTime(new Date());
                businessData.setCid(ShiroUtils.getMandatorCid());
                businessData.setCidName(ShiroUtils.getMandatorCidName());
                businessData.setbUser(ShiroUtils.getMandatorId());
                businessData.setbUserName(ShiroUtils.getMandatorName());
                businessData.setbDept(ShiroUtils.getMandatorDeptPath());
                businessData.setbDeptName(ShiroUtils.getMandatorDeptName());
                businessData.setbPosition(ShiroUtils.getMandatorPositionNameDa());
                businessData.setaUser(ShiroUtils.getUserId());
                businessData.setaUserName(ShiroUtils.getUserName());
                businessData.setaDept(ShiroUtils.getUserDeptPath());
                businessData.setaDeptName(ShiroUtils.getUserDeptName());
                businessData.setaPosition(ShiroUtils.getUserPositionNameDa());
                businessData.setSjAmount(BigDecimal.ZERO);
                businessData.setXtAmount(BigDecimal.ZERO);
                businessData.setDzFiles("无附件");
                headData = TypeUtils.entityToMap(businessData);
            } else {
                headData = TypeUtils.entityToMap(businessData);
                vType = businessData.getEffectStock();
            }
            params.put("headData", headData); //表头的业务数据

            params.put("checkBox", "yes"); //生成表格gridColumns时包含复选
            ModelAndView mv = this.openEditPage(params);
            mv.addObject("nowTimeStr", DateUtils.getDate());    //当前日期
            mv.addObject("enableEdit", vType ? 0 : enableEdit); //当前页面是否可编辑（0：不可编辑，1：可编辑）
            if (businessData != null) {
                Map<String, Object> params3 = new HashMap<String, Object>();
                params3.put("pBid",businessData.getBid());
                params3.put("moduleTable", moduleTable2);
                mv.addObject("List", hwReconcileSonService.queryList(params3));//子件数据

                params3.put("moduleTable", moduleTable3);
                mv.addObject("CkList", hwReconcileCksonService.queryList(params3));//出库数据

                params3.put("moduleTable", moduleTable4);
                mv.addObject("KcList", hwReconcileKcsonService.queryList(params3));//库存数据
            }
            //取子件列表网格
            params.put("moduleTable", moduleTable2);
            params.put("entity", new HwReconcileSon()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
            params.put("readOnly", vType);//生成列是否可编辑
            params.put("toolBarWidth", 0);//操作区
            params.put("checkBox", "yes");
            params.put("getFieldAttributesType", "pageingrid");//pageingrid：网格字段
            mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
            mv.addObject("importFields", dictionaryForFieldService.queryFieldFrontImport(params));	//导入模板字段


            params.put("moduleTable", moduleTable3);
            params.put("entity", new HwReconcileCkson());
            params.put("readOnly", vType);//生成列是否可编辑
            params.put("toolBarWidth", 0);//操作区
            params.put("checkBox", "yes");
            params.put("getFieldAttributesType", "pageingrid");//pageingrid：网格字段
            mv.addObject("gridColumnsCk", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
            mv.addObject("importCk", dictionaryForFieldService.queryFieldFrontImport(params));


            params.put("moduleTable", moduleTable4);
            params.put("entity", new HwReconcileKcson());
            params.put("readOnly", vType);//生成列是否可编辑
            params.put("toolBarWidth", 0);//操作区
            params.put("checkBox", "yes");
            params.put("getFieldAttributesType", "pageingrid");//pageingrid：网格字段
            mv.addObject("gridColumnsKc", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
            mv.addObject("importF", dictionaryForFieldService.queryFieldFrontImport(params));
            return mv;
        } catch (Exception e) {
            return this.gotoModelAndViewErrorPage(e.getMessage());    //详细信息
        }
    }

    /**
     *@Description: 查询前一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult (data.nid 前一单NID， data.bid 前一单BID)
     *@Author: fxz
     *@date: 2024-03-01 11:09:34
     */
    @RequiresPermissions("storage:hwReconcile:view")
    @GetMapping("/lastnid")
    @ResponseBody
    public AjaxResult lastNid(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = hwReconcileService.queryLastNid(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 查询后一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult (data.nid 后一单NID， data.bid 后一单BID)
     *@Author: fxz
     *@date: 2024-03-01 11:09:34
     */
    @RequiresPermissions("storage:hwReconcile:view")
    @GetMapping("/nextnid")
    @ResponseBody
    public AjaxResult nextNid(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = hwReconcileService.queryNextNid(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * @Description: 保存数据
     * @Param: infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: fxz
     * @date: 2024-03-01 11:09:34
     */
    @RequiresPermissions(value = {"storage:hwReconcile:add", "storage:hwReconcile:edit", "storage:hwReconcile:delete"}, logical = Logical.OR)
    @Log(title = "海外仓对账单", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editpost(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = hwReconcileService.saveData(params);
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 打开流转页
     * @param fType 必要参数：审核类型（flow_go：流转，flow_back：退回）
     * @param infoMap 必要参数：非网格字段（包括所有显示和隐藏的字段），json格式字符串
     * @return
     * @author fxz
     */
    @RequiresPermissions("storage:hwReconcile:flow")
    @PostMapping("/flowpage")
    @ResponseBody
    public AjaxResult flowPage(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("prefix", prefix);
        return openFlowPage(params);
    }

    /**
     *@Description: 流转
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] infoItems 必要参数：对应实体类的json格式字符串（仅需 guid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: fxz
     *@date: 2024-03-01 11:09:34
     */
    @RequiresPermissions("storage:hwReconcile:flow")
    @Log(title = "海外仓对账单", businessType = BusinessType.FLOWGO)
    @PostMapping("/flowgopost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult flowGoSave(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= hwReconcileService.updateFlowGo(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 退回
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] 必要参数：对应实体类的json格式字符串（仅需 guid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: fxz
     *@date: 2024-03-01 11:09:34
     */
    @RequiresPermissions("storage:hwReconcile:flow")
    @Log(title = "海外仓对账单", businessType = BusinessType.FLOWBACK)
    @PostMapping("/flowbackpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult flowBackSave(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= hwReconcileService.updateFlowBack(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 子件数据
     *@Author: fxz
     *@date: 2024-03-01 11:09:34
     */
    @GetMapping("/sonList")
    @ResponseBody
    public AjaxResult sonList(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= hwReconcileService.sonList(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 导出Excel导入模板
     * @param params
     * @return
     * @throws Exception
     * @author fxz
     */
    @RequiresPermissions("storage:hwReconcile:import")
    @Log(title = "海外仓对账数据导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exporttemplate")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult exportTemplate(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable2);
        params.put("entity", new HwReconcileSon());
        String sheetName = "入库对账导入模板";
        if (params.get("num").equals("5")){
            params.put("moduleTable", moduleTable4);
            params.put("entity", new HwReconcileKcson());
            sheetName = "库存对账模板";
        }else if (params.get("num").equals("6")){
            params.put("moduleTable", moduleTable3);
            params.put("entity", new HwReconcileCkson());
            sheetName = "出库对账模板";
        }
        params.put("getFieldAttributesType", "template");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);

        ExportExcelUtils<HwReconcile> util = new ExportExcelUtils<HwReconcile>(moduleTable2,new HwReconcile());
        return util.exportExcel(null, fieldList, sheetName, "template");
    }

    /**
     * @Description: 查询页 列表数据
     * @Param: [params]
     * @return: com.dhecp.common.core.page.TableDataInfo
     * @Author: fxz
     * @date: 2023-06-08
     */
    @RequiresPermissions("storage:hwReconcile:list")
    @GetMapping("/hwReconcileList")
    @ResponseBody
    public TableDataInfo hwFinalStatementList(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        List<HwReconcileSelect> list = new ArrayList<HwReconcileSelect>();
        List<HwPaymentson> hwPaymentsonList = hwPaymentSonMapper.queryListCode(params.get("bid").toString());
        StringBuffer sb = new StringBuffer();
        for (HwPaymentson hwPaymentson : hwPaymentsonList){
            sb.append(hwPaymentson.getDzBid()).append(",");
        }
        String codereconcile = " (t1.stateName = '已对账')";
        if (sb.length() != 0){
            String sb1 = sb.toString().substring(0,sb.length()-1);
            codereconcile = "t1.bid in ('" + sb1.replace(",", "','") + "')";
        }
        params.put("codereconcile", codereconcile);
//
        try {
            list = hwReconcileService.queryListSelect(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     *@Description: 查询已选择的商品
     *@Param: selectedUser ：已选中的商品编号字符串，示例：0000,1001,1002
     *@return: com.dhecp.common.core.page.TableDataInfo
     *@Author: hlf
     *@date: 2022-08-18 17:13
     */
    @GetMapping("/listselect")
    @ResponseBody
    public TableDataInfo userInfoSelectListJson(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        List<HwReconcileSelect> list = new ArrayList<HwReconcileSelect>();
        if (params.get("selectedUser") != null && params.get("selectedUser") != ""){
            String wherestrhand = "t1.bid in ('" + params.get("selectedUser").toString().replace(",", "','") + "')";
            params.put("wherestrhand", wherestrhand);
            try{
                list = hwReconcileService.queryListSelect(params);
            }catch(Exception e){
                return getDataTable(this.getExceptionMessage(e).toString());
            }
        }else{
            return getDataTable("请传入已选中的商品编码字符串（selectedUser），取值示例：0000,1001,1002");
        }
        return getDataTable(list);
    }
}

